<template>
  <div class="contain">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-form
          class="login-form"
          :rules="rules"
          :model="form"
          ref="loginForms"
        >
          <h1>hello</h1>
          <h2>欢迎您的到来</h2>
          <el-form-item prop="username">
            <el-input v-model="form.username" :prefix-icon="User"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="form.password"
              type="password"
              show-password
              :prefix-icon="Lock"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              :loading="loading"
              type="primary"
              size="default"
              class="login-btn"
              @click="login"
            >
              登 录
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { Lock, User } from '@element-plus/icons-vue'
import { reactive, ref } from 'vue'
import { ElNotification } from 'element-plus'
import useUserStore from '@/store/modules/user'
import { useRouter, useRoute } from 'vue-router'
import getTime from '@/utils/getTime'
const $router = useRouter()
const $route = useRoute()
let loading = ref<Boolean>(false)
const userStore = useUserStore()
const form = reactive({
  username: 'admin',
  password: 'atguigu123',
})
const rules = reactive({
  username: [
    { required: true, min: 5, message: '用户名最小为5位', trigger: 'change' },
  ],
  password: [
    { required: true, min: 6, message: '密码最小为6位', trigger: 'change' },
  ],
})
const loginForms = ref()
const login = async () => {
  await loginForms.value.validate()
  loading.value = true
  try {
    await userStore.login(form)
    //显示登陆成功
    ElNotification({
      message: '欢迎回来',
      type: 'success',
      title: `HI,${getTime()}`,
    })
    //跳转路由
    let redirect = $route.query.redirect
    if (redirect) {
      $router.push(redirect)
    } else {
      $router.push('/')
    }
    loading.value = false
  } catch (error) {
    ElNotification({
      message: error.message,
      type: 'error',
    })
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
.contain {
  width: 100%;
  height: 100vh;
  background: url('@/assets/images/background.jpg') no-repeat;
  background-size: cover;

  .login-form {
    position: relative;
    top: 30vh;
    width: 80%;
    background: url('@/assets/images/login_form.png') no-repeat;
    background-size: cover;
    padding: 40px 40px;

    h1 {
      color: white;
      font-size: 40px;
    }

    h2 {
      color: white;
      font-size: 20px;
      margin: 20px 0px;
    }

    .login-btn {
      width: 100%;
    }
  }
}
</style>
